package com.example.asynctask;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
	Context mContext;
	Button mLoadButton;
	ImageView mImageframe;
	
	Bitmap image;
	
	AsyncTask<Integer, Float, Boolean> loadImageTask = new AsyncTask<Integer, Float, Boolean>(){
		long startTime;
		
		@Override
		protected void onPreExecute(){
			//Before doing any computation,
			//keep track of the start time for
			//comparison with Runnable and no
			//multithreading.
			startTime = System.currentTimeMillis();
		}
		
		@Override
		protected Boolean doInBackground(Integer... imageResources) {
			//This example only loads one of
			//the images, so choose the first one
			
			if(imageResources == null ||
			   imageResources.length < 1) {
				//There are no images to load
				return false;
			}
			
			if(isCancelled()){
				//The task was cancelled
				return false;
			}
			
			if(image != null){
				//Save memory if
				//the image was already
				//loaded
				image.recycle();
			}
			
			//Load the image
			image = BitmapFactory.decodeResource(
					   mContext.getResources(),
					   imageResources[0]);
			
			//Update the progress
			//(this will result in
			// onProgressUpdate being
			// called)
			publishProgress(1f);
			
			//The image was loaded succesfully
			return true;
		}
		
		@Override
		protected void onProgressUpdate(Float... progress){
			//This example is only loading one image,
			//so there is no need to update a 
			//progress bar
			Log.d("loadImageTask","Progess: " + (progress[0] * 100) + "%");
		}
		
		@Override
		protected void onPostExecute(Boolean result){
			if(result){
				//The image was loaded successfully.
				//Set the image frame to display
				//the loaded image
				mImageframe.setImageBitmap(image);
				
				//Log out the time it took to display
				long loadTime = System.currentTimeMillis() - startTime;
				Log.d("loadImageTask","Loaded Image successfully");
				Log.d("loadImageTask","Time to load: "+loadTime);
			}else{
				Log.e("loadImageTask", "Problem loading image");
			}
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mContext = this;
		
		mImageframe = (ImageView) findViewById(R.id.image_frame);
		
		mLoadButton = (Button) findViewById(R.id.load_image_button);
		mLoadButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				//Execute the task with the
				//space image resource as
				//an argument
				loadImageTask.execute(R.drawable.space);				
			}
		});
	}
	
}
